package com.hkts.management.message.nettyhandler;

import com.alibaba.fastjson.JSON;
import com.hkts.management.message.constants.MessageConstants;
import com.hkts.management.message.msg.sendUtil.NettySendUtil;
import com.hkts.management.message.msg.sendUtil.ResultMsg;
import com.hkts.management.message.msg.service.serviceimpl.MsgTemplateServiceImpl;
import com.hkts.management.message.utils.SpringContextHolder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * MyWebSocketHandler
 * WebSocket处理器，处理websocket连接相关
 * @author zhengkai.blog.csdn.net
 * @date 2019-06-12
 */
@Slf4j
public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("与客户端建立连接，通道开启！");
        //添加到channelGroup通道组
        MyChannelHandlerPool.channelGroup.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("与用户[{}]断开连接，通道关闭！",MyChannelHandlerPool.getUserId(ctx.channel().id().toString()));
        //删除通道
        MyChannelHandlerPool.removeChannel(ctx.channel().id().toString());
        //从channelGroup 通道组删除
        MyChannelHandlerPool.channelGroup.remove(ctx.channel());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //首次连接是FullHttpRequest，处理参数 by zhengkai.blog.csdn.net
        if (null != msg && msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();

            Map paramMap= NettySendUtil.getUrlParams(uri);
            log.info("接收到的参数是：{}", JSON.toJSONString(paramMap));
            //如果url包含参数，需要处理
            if(uri.contains("?")){
                String newUri=uri.substring(0,uri.indexOf("?"));
                log.info("url：{}",newUri);
                request.setUri(newUri);
            }
            /*
             * 将参数及Channel id 缓存到redis
             * */
            if(paramMap.get("paramterType").toString().equals("user")){
                MyChannelHandlerPool.addChannel(paramMap.get("id").toString(),ctx);
//                StringRedisTemplate bean = SpringUtils.getBean(StringRedisTemplate.class);
//                bean.opsForValue().set(MessageConstants.USER_MQ+paramMap.get("id").toString(),ctx.channel().id().asLongText());
            }
        }else if(msg instanceof TextWebSocketFrame){
            //正常的TEXT消息类型
            TextWebSocketFrame frame=(TextWebSocketFrame)msg;
            String test=frame.text();

            if (MessageConstants.PING_MSG.equals(test)) {
                NettySendUtil.sendPongMsg(ctx);
                return;
            }
            log.info("获取客户端数据：{}",test);
            String[] ids=test.split("-");
            if ("getTotalNews".equals(ids[0])) {
                MsgTemplateServiceImpl msgTemplateService=SpringContextHolder.getBean(MsgTemplateServiceImpl.class);
                msgTemplateService.sendSubscript(ids[1]);
                return;
            }
            ResultMsg resultMsg=new ResultMsg();
            resultMsg.setMessage(test);
            NettySendUtil.sendAllMessage(resultMsg);
        }
        super.channelRead(ctx, msg);

    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

    }


}